package com.shuaiche.yeguan.net.oss;

import android.net.Uri;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.shuaiche.yeguan.config.SCAppConfig;
import com.shuaiche.yeguan.util.LogUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;


public class MultiImagesUploadManager {

    private int length = 0;
    private int imagePathsLength = 0;
    private List<PutObjectRequest> successRequests = new ArrayList<PutObjectRequest>();

    private MultiImagesUploadCallback mMultiImagesUploadCallback;

    public void setMultiImagesUploadCallback(MultiImagesUploadCallback callback){
        mMultiImagesUploadCallback = callback;
    }

    OSSUploadCallback mOSSUploadCallback = new OSSUploadCallback() {
        @Override
        public void onSuccess(List<PutObjectRequest> requests, List<PutObjectResult> results) {
            LogUtils.log("OSSUploadCallback onSuccess");
            length++;
            successRequests.addAll(requests);
            if(length==imagePathsLength){
                mMultiImagesUploadCallback.onSuccess(successRequests);
            }

        }

        @Override
        public void onFailure(PutObjectRequest request, Exception excepion) {
            LogUtils.log("OSSUploadCallback onFailure");
            mMultiImagesUploadCallback.onFailure(successRequests);
        }
    };

    public void startUpload(ArrayList<String> imagePaths, MultiImagesUploadCallback callback,
                            String accessKeyId, String accessKeySecret, String securityToken , int ossType){
        startUpload(imagePaths, null, callback, accessKeyId, accessKeySecret, securityToken, ossType);
    }

    public void startUpload(ArrayList<String> imagePaths, List<PutObjectRequest> lastSuccessRequests, MultiImagesUploadCallback callback,
                            String accessKeyId, String accessKeySecret, String securityToken, int ossType){
        mMultiImagesUploadCallback = callback;
        successRequests.clear();
        Iterator<String> ite = imagePaths.iterator();
        while (ite.hasNext()){
            String s = ite.next();
            if(s.startsWith("http")){
                ite.remove();
            }
        }

        if(lastSuccessRequests!=null && lastSuccessRequests.size()>0){
            successRequests = lastSuccessRequests;
            for(PutObjectRequest mPutObjectRequest:lastSuccessRequests){
                if(imagePaths.contains(mPutObjectRequest.getUploadFilePath())){
                    imagePaths.remove(mPutObjectRequest.getUploadFilePath());
                }
            }
        }
        imagePathsLength = imagePaths.size();
        if(imagePathsLength==0){
            mMultiImagesUploadCallback.onSuccess(successRequests);
            return;
        }
        length = 0;
        OSSUploadManager mOSSUploadManager = new OSSUploadManager(accessKeyId, accessKeySecret, securityToken);

        for(String sPath:imagePaths){
            String mObjectKey = getImagePathPre(ossType) + UUID.randomUUID().toString().replace("-", "")+".jpg";
            OSSRequestBody mOSSRequestBody =
                    new OSSRequestBody.Builder("imgrep", mObjectKey, sPath).build();
            mOSSUploadManager.asyncUploadBitmap(mOSSRequestBody, mOSSUploadCallback);
        }
    }


    public void startUploadNoCompress(ArrayList<String> imagePaths, MultiImagesUploadCallback callback,
                            String accessKeyId, String accessKeySecret, String securityToken , int ossType){
        startUploadNoCompress(imagePaths, null, callback, accessKeyId, accessKeySecret, securityToken, ossType);
    }
    public void startUploadNoCompress(ArrayList<String> imagePaths, List<PutObjectRequest> lastSuccessRequests, MultiImagesUploadCallback callback,
                            String accessKeyId, String accessKeySecret, String securityToken, int ossType){
        mMultiImagesUploadCallback = callback;
        successRequests.clear();
        Iterator<String> ite = imagePaths.iterator();
        while (ite.hasNext()){
            String s = ite.next();
            if(s.startsWith("http")){
                ite.remove();
            }
        }

        if(lastSuccessRequests!=null && lastSuccessRequests.size()>0){
            successRequests = lastSuccessRequests;
            for(PutObjectRequest mPutObjectRequest:lastSuccessRequests){
                if(imagePaths.contains(mPutObjectRequest.getUploadFilePath())){
                    imagePaths.remove(mPutObjectRequest.getUploadFilePath());
                }
            }
        }
        imagePathsLength = imagePaths.size();
        if(imagePathsLength==0){
            mMultiImagesUploadCallback.onSuccess(successRequests);
            return;
        }
        length = 0;
        OSSUploadManager mOSSUploadManager = new OSSUploadManager(accessKeyId, accessKeySecret, securityToken);

        for(String sPath:imagePaths){
            String mObjectKey = getImagePathPre(ossType) + UUID.randomUUID().toString().replace("-", "")+".jpg";
            OSSRequestBody mOSSRequestBody =
                    new OSSRequestBody.Builder("imgrep", mObjectKey, sPath).build();
            mOSSUploadManager.asyncUpload(mOSSRequestBody, mOSSUploadCallback);
        }
    }

    public void startUploadPDF(ArrayList<String> imagePaths, List<PutObjectRequest> lastSuccessRequests, MultiImagesUploadCallback callback,
                            String accessKeyId, String accessKeySecret, String securityToken, int ossType,String MD5){
        mMultiImagesUploadCallback = callback;
        successRequests.clear();
        Iterator<String> ite = imagePaths.iterator();
        while (ite.hasNext()){
            String s = ite.next();
            if(s.startsWith("http")){
                ite.remove();
            }
        }

        if(lastSuccessRequests!=null && lastSuccessRequests.size()>0){
            successRequests = lastSuccessRequests;
            for(PutObjectRequest mPutObjectRequest:lastSuccessRequests){
                if(imagePaths.contains(mPutObjectRequest.getUploadFilePath())){
                    imagePaths.remove(mPutObjectRequest.getUploadFilePath());
                }
            }
        }
        imagePathsLength = imagePaths.size();
        if(imagePathsLength==0){
            mMultiImagesUploadCallback.onSuccess(successRequests);
            return;
        }
        length = 0;
        OSSUploadManager mOSSUploadManager = new OSSUploadManager(accessKeyId, accessKeySecret, securityToken);

        for(String sPath:imagePaths){
            String mObjectKey = getPDFPathPre(ossType) + MD5 + ".pdf";
            OSSRequestBody mOSSRequestBody =
                    new OSSRequestBody.Builder("imgrep", mObjectKey, sPath).contentType("application/pdf").build();
            mOSSUploadManager.asyncUpload(mOSSRequestBody,mOSSUploadCallback);
        }
    }


    public void startUploadPDFByUri(Uri uri, MultiImagesUploadCallback callback,
                                       String accessKeyId, String accessKeySecret, String securityToken, int ossType){
        mMultiImagesUploadCallback = callback;
        successRequests.clear();
        imagePathsLength = 1;
        length = 0;
        OSSUploadManager mOSSUploadManager = new OSSUploadManager(accessKeyId, accessKeySecret, securityToken);
        String mObjectKey = getPDFPathPre(ossType) +System.currentTimeMillis()+ UUID.randomUUID().toString().replace("-", "") +".pdf";
        OSSRequestBody mOSSRequestBody =
                new OSSRequestBody.Builder("imgrep", mObjectKey, uri).contentType("application/pdf").build();
        mOSSUploadManager.asyncUploadByUri(mOSSRequestBody,mOSSUploadCallback);
    }

    public void startUploadIMFile(String filePath, MultiImagesUploadCallback callback,
                               String accessKeyId, String accessKeySecret, String securityToken, int ossType,String fileEnd){
        mMultiImagesUploadCallback = callback;
        successRequests.clear();
        imagePathsLength = 1;
        length = 0;
        OSSUploadManager mOSSUploadManager = new OSSUploadManager(accessKeyId, accessKeySecret, securityToken);
        String mObjectKey = getIMPathPre(ossType) +System.currentTimeMillis()+ UUID.randomUUID().toString().replace("-", "") +"."+ fileEnd;
        OSSRequestBody mOSSRequestBody =
                new OSSRequestBody.Builder("scim", mObjectKey, filePath).build();
        mOSSUploadManager.asyncUpload(mOSSRequestBody,mOSSUploadCallback);
    }

    public void startUploadIMFileByUri(Uri uri, MultiImagesUploadCallback callback,
                                       String accessKeyId, String accessKeySecret, String securityToken, int ossType, String fileEnd){
        mMultiImagesUploadCallback = callback;
        successRequests.clear();
        imagePathsLength = 1;
        length = 0;
        OSSUploadManager mOSSUploadManager = new OSSUploadManager(accessKeyId, accessKeySecret, securityToken);
        String mObjectKey = getIMPathPre(ossType) +System.currentTimeMillis()+ UUID.randomUUID().toString().replace("-", "") +"."+ fileEnd;
        OSSRequestBody mOSSRequestBody =
                new OSSRequestBody.Builder("scim", mObjectKey, uri).build();
        mOSSUploadManager.asyncUploadByUri(mOSSRequestBody,mOSSUploadCallback);
    }

    /**
     * 获取IM文件前缀
     * @param ossType
     * @return
     */
    public String getIMPathPre(int ossType) {
        String prefix = "";
        if (SCAppConfig.IS_DEBUG) {
            prefix = "temp/";
        }
        if (ossType == SCAppConfig.OSS_IM_MEDIA) {
            return prefix + "image/";

        } else if (ossType == SCAppConfig.OSS_IM_SOUND){
            return prefix + "sound/";
        }else {
            return prefix + "file/";
        }
    }

    /**
     * 上传图片
     * 获取图片路径前缀
     */
    private String getImagePathPre(int ossType) {
        String prefix = "img/";     //release 环境
        if (SCAppConfig.IS_DEBUG) {
            prefix = "temp/";       //debug环境
        }

        if (ossType == SCAppConfig.OSS_LICENSE) {       //资质认证
            return prefix + "license/";
        } else if (ossType == SCAppConfig.OSS_FACE){    //头像
            return prefix + "face/";
        } else {
            //上传车辆图片
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMM");
            Date date=new Date();
            return prefix + sdf.format(date) + "/";
        }
    }

    /**
     * PDF文件前缀
     */
    public String getPDFPathPre(int ossType) {
        String prefix = "";
        if (SCAppConfig.IS_DEBUG) {
            prefix = "temp/";
        }
        prefix = prefix + "file/car/";
        if (ossType == SCAppConfig.OSS_PDF_TESTREPORT) {
            return prefix + "testreport/";

        } else {
            return prefix + "maintainreport/";
        }
    }


    public interface MultiImagesUploadCallback {

        /**
         * 成功反馈
         * @param requests 上传的数据集
         */
        void onSuccess(List<PutObjectRequest> requests);

        /***
         * 失败反馈
         * @param requests
         */
        void onFailure(List<PutObjectRequest> requests);
    }

}
